package net.uofitorn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class AsteroidRunnerServerThread implements Runnable
{
	private Socket socket;
	private AsteroidRunnerServerMain callback;
	BufferedReader in;
	PrintWriter out;
	int playerID;
	int otherPlayerID;
	int connectedID;
	AsteroidRunnerServerThread otherPlayerThread;
	
	public AsteroidRunnerServerThread(Socket socket, AsteroidRunnerServerMain serverMain, int playerID, int connectedId) {
		this.socket = socket;
		this.callback = serverMain;
		this.playerID = playerID;
		this.connectedID = connectedID;
		if (playerID == 1)
			this.otherPlayerID = 2;
		else
			this.otherPlayerID = 1;
	}

	public void sendStartMessage(AsteroidRunnerServerThread otherPlayerThread) {
		this.otherPlayerThread = otherPlayerThread;
		//while(out == null)
		//	;;
		//out.println("READY");
	}
	
	public void sendPlayerNumber(int playerNumber) {
		String playerNumberString = Integer.toString(playerNumber);
		String message = "{\"command\":\"playerNumber\",\"playerNumber\":\"" + playerNumberString + "\"}";
		System.out.println("Sending message: " + message);
		sendMessage(message);
	}
	
	public void sendMessage(String message) {
		while (out == null) 
			;;
		out.println(message);
	}
	
	public void run () {
		try {
			in = new BufferedReader (new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
			
			while (true) {
				System.out.println("Player " + playerID + " listening for messages.");
		        String message = in.readLine();
		        
		        if (message == null || message.equalsIgnoreCase("99")) {
		        	System.out.println("In thread, sending endThread() and closing socket");
		        	callback.endThread(connectedID);
		        	socket.close();
		        	break;
		        }
		        
		        System.out.println("Player " + playerID + " received message: " + message + ". Sending to other player.");
		        otherPlayerThread.sendMessage(message);
		    }
		} catch (Exception e) {
			System.out.println("Caught exception in thread: " + e.toString());
		} finally {
			try {
				out.println("Thread received 99 from client");
				socket.close();
			} catch (IOException e) {
				
			}
		}
	}   
}
